﻿using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Xml;

namespace SourceGenerator
{
    [Generator]
    public class HelloSourceGenerator : ISourceGenerator
    {
        public void Execute(GeneratorExecutionContext context)
        {
            //Debugger.Launch();
            // Find the main method
            var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);

            //Console.WriteLine(JsonConvert.SerializeObject(mainMethod, Newtonsoft.Json.Formatting.Indented));
            // Build up the source code
            string source = $@"// <auto-generated/>
            using System;
            namespace {mainMethod.ContainingNamespace.ToDisplayString()}
            {{
                public static partial class {mainMethod.ContainingType.Name}
                {{
                    static partial void HelloCode(string name) =>
                        Console.WriteLine($""Generator says: Hi from '{{name}}'"");

                    static partial void AdditionOperation(int num1, int num2) =>
                        Console.WriteLine($""求和计算结果如下:{{(num1+num2)}}"");

                    static partial void ArryOperation(List<int> ints) 
                    {{
                       foreach (int i in ints)
                       {{
                            Console.WriteLine($""输出集合结果:{{i}}"");
                        }}
                    }}
                }}
            }}
            ";
            var typeName = mainMethod.ContainingType.Name;

            // Add the source code to the compilation
            context.AddSource($"{typeName}.g.cs", source);
        }

        public void Initialize(GeneratorInitializationContext context)
        {
            // No initialization required for this one
        }
    }

}
